#!/usr/bin/env bun

/**
 * Build script for protoactor-ts using Bun
 * This script builds the project and handles TypeScript transpilation
 */

import { spawnSync } from 'child_process';
import { mkdir } from 'fs/promises';

// First ensure dist directory exists
try {
  await mkdir('./dist', { recursive: true });
  console.log('✅ Created dist directory');
} catch (error) {
  console.log('Directory already exists or could not be created');
}

// Run TypeScript compiler for type checking and declaration files
console.log('🔍 Running TypeScript compiler for type checking and declarations...');
const tscResult = spawnSync('bun', ['x', 'tsc', '--emitDeclarationOnly', '--declaration'], { 
  stdio: 'inherit', 
  shell: true 
});

if (tscResult.status !== 0) {
  console.error('❌ TypeScript compilation failed');
  process.exit(1);
}

// Build with Bun
console.log('🏗️ Building with Bun...');
const buildResult = await Bun.build({
  entrypoints: ['./src/index.ts'],
  outdir: './dist',
  target: 'node',
  format: 'esm',
  sourcemap: 'external',
  minify: process.env.NODE_ENV === 'production',
});

if (!buildResult.success) {
  console.error('❌ Build failed:', buildResult.logs);
  process.exit(1);
}

console.log('✅ Build completed successfully!'); 